package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.SetmealDTO;
import com.sky.dto.SetmealPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.SetmealEnableFailedException;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.SetmealService;
import com.sky.vo.SetmealVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 套餐业务
 */
@Service
@Slf4j
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private DishMapper dishMapper;
    /**
     * 新增套餐
     * @param setmealDTO
     */
    @Transactional
    @CacheEvict(cacheNames = "setmeal",key = "#setmealDTO.categoryId")
    public void addSetmeal(SetmealDTO setmealDTO) {
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO,setmeal);
        //向套餐表插入一条数据，主键回显
        setmealMapper.insertSetmeal(setmeal);
        Long setmealId = setmeal.getId();
        List<SetmealDish> setmealDishList = setmealDTO.getSetmealDishes();
        setmealDishList.stream().forEach(setmealDish -> setmealDish.setSetmealId(setmealId));
        //向套餐菜品中间表插入N条
        setmealDishMapper.inertBatchSetmealDish(setmealDishList);
    }

    /**
     * 套餐分页条件查询
     * @param setmealPageQueryDTO
     * @return
     */
    public PageResult setmealPage(SetmealPageQueryDTO setmealPageQueryDTO) {
        PageHelper.startPage(setmealPageQueryDTO.getPage(),setmealPageQueryDTO.getPageSize());
        Page<SetmealVO> page = setmealMapper.setmealPage(setmealPageQueryDTO);
        return new PageResult(page.getTotal(),page);
    }

    /**
     * 修改套餐
     * @param setmealDTO
     */
    @Transactional
    @CacheEvict(cacheNames = "setmeal",key = "#setmealDTO.categoryId")
    public void updateSetmealById(SetmealDTO setmealDTO) {
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO,setmeal);

        setmealMapper.updateSetmealById(setmeal);
        //删除中间表，重新插入
        Long setmealId = setmealDTO.getId();
        log.info("当前套餐id为：{}",setmealId);
        setmealDishMapper.deleteSetmealDishBySetmealId(setmealId);

        List<SetmealDish> setmealDishList = setmealDTO.getSetmealDishes();
        setmealDishList.stream().forEach(setmealDish -> setmealDish.setSetmealId(setmealId));

        setmealDishMapper.inertBatchSetmealDish(setmealDishList);
    }


    /**
     * 根据id查询套餐
     * @param id
     * @return
     */
    public SetmealVO getSetmealWithDishById(Long id) {
        Setmeal setmeal = setmealMapper.getSetmealById(id);


        List<SetmealDish> setmealDishList = setmealDishMapper.getSetmealDishById(id);
        SetmealVO setmealVO = new SetmealVO();
        BeanUtils.copyProperties(setmeal,setmealVO);
        setmealVO.setSetmealDishes(setmealDishList);
        return setmealVO;
    }

    /**
     * 修改套餐状态
     * @param status
     * @param id
     */
    @CacheEvict(cacheNames = "setmeal",allEntries = true)
    public void updateSetmealStatus(Integer status, Long id) {
        //根据套餐id查菜品状态
        /*String msg = checkDishStatusBySetmealId(id);
        log.info("是否起售成功:  {}",msg);*/
        List<SetmealDish> setmealDishList = setmealDishMapper.getSetmealDishById(id);
        List<Long> DishIds = new ArrayList<>();
        setmealDishList.forEach(setmealDish -> DishIds.add(setmealDish.getDishId()));

        List<Dish> dishList = new ArrayList<>();
        DishIds.forEach(DishId ->{
            Dish dish = dishMapper.getDishById(DishId);
            dishList.add(dish);
        });
        long count = dishList.stream().filter(dish -> dish.getStatus().equals(StatusConstant.DISABLE)).count();
        if (count > 0){
            throw new SetmealEnableFailedException(MessageConstant.SETMEAL_ENABLE_FAILED);
        }else {
            Setmeal setmeal = Setmeal.builder()
                    .id(id)
                    .status(status)
                    .build();
            setmealMapper.updateSetmealById(setmeal);
        }
    }


    public String checkDishStatusBySetmealId(Long id){
        //根据套餐id查菜品状态
        List<SetmealDish> setmealDishList = setmealDishMapper.getSetmealDishById(id);
        List<Long> dishIdList = new ArrayList<>();
        setmealDishList.forEach(setmealDish -> {
            dishIdList.add(setmealDish.getDishId());
        });

        dishIdList.forEach(dishId -> {
                    Dish dish = dishMapper.getDishById(dishId);
                    if (dish.getStatus() == 0){
                        throw new SetmealEnableFailedException(MessageConstant.SETMEAL_ENABLE_FAILED);
                    }
                }
        );
        return MessageConstant.DISHSTATUS;
    }

    /**
     * 批量删除套餐
     * @param ids
     */
    @Transactional
    @CacheEvict(cacheNames = "setmeal",allEntries = true)
    public void deleteBatchSetmeal(List<Long> ids) {
        //起售中的套餐无法删除
       int count = setmealMapper.getSetmealOnSale(ids);
       if (count > 0){
           throw new DeletionNotAllowedException(MessageConstant.SETMEAL_ON_SALE);
       }

       //删除套餐和中间便
        dishMapper.deleteBatchSetmeal(ids);

        ids.forEach(id -> {
            setmealDishMapper.deleteSetmealDishBySetmealId(id);
        });
    }

    /**
     * 根据分类Id查询套餐
     * @param setmeal
     * @return
     */
    @Cacheable(cacheNames = "setmeal",key = "#setmeal.categoryId")
    public List<Setmeal> getSetmealByCategoryId(Setmeal setmeal) {
        return setmealMapper.getSetmealByCategoryId(setmeal);
    }
}
